<?php

namespace App\Handlers;

use GuzzleHttp\Client;

class GetViewCountHandler
{
    // $user_ids = [] 用户ID数组
    public function get($user_ids)
    {
        $http = new Client;

        $api = 'https://mta.qq.com/h5/api/ctr_custom?';

        $custom = $user_ids;

        $params = [
            'app_id' => config('services.tx_tongji.appid') ?: setting('sid'),
            'custom' => $custom,
            'start_date' => date('Y-m-d'),
            'end_date' => date('Y-m-d'),
            'idx' => 'iv'
        ];
        $sign = $this->makeSign($params);
        $params['sign'] = $sign;

        $query = http_build_query($params);
        // 发送 HTTP Get 请求
        // $api = route('views.test') . '/?';
        $response = $http->get($api.$query);

        $result = json_decode($response->getBody(), true);
        if ($result['code'] === 0 && $result['info'] === 'success') {
            return $result['data'];
        }
        return false;
    }

    protected function makeSign($params)
    {
        $secret_key = config('services.tx_tongji.appkey') ?: setting('mta_appkey');
        ksort($params);
        foreach ($params as $key => $value) {
            $secret_key .= $key . '=' . $value;
        }
        $sign = md5($secret_key);
        return $sign;
    }
}
